package com.ruoyi.jxxwx.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jxxwx.service.IJxxcoderWxuserService;
import com.ruoyi.jxxwx.utils.HttpUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/wxapi")
public class WxLoginController {

    /**
     * 测试接口
     * @return
     */
    @GetMapping("/test")
    public R test(){
        return R.ok("小程序api调试成功！~");
    }

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IJxxcoderWxuserService iJxxcoderWxuserService;


    /**
     * 你自己的微信小程序APPID
     */

    private final static String AppID = "wx4c82a5af118912bc";
    /**
     * 你自己的微信APP密钥
     */
    private final static String AppSecret = "7dbf654316c4d5fee956b5e5470e50bb";

    /**
     * 登录时获取的 code（微信官方提供的临时凭证）
     * @param object
     * @return
     */
    @SaIgnore
    @PostMapping("/wxlogin")
    public R wxLogin(@RequestBody JSONObject object){
        //微信官方提供的微信小程序登录授权时使用的URL地址
        String url  = "https://api.weixin.qq.com/sns/jscode2session";
        System.out.println(object);

        /**
         * 拼接需要的参数
         * appid = AppID 你自己的微信小程序APPID
         * js_code = AppSecret 你自己的微信APP密钥
         * grant_type=authorization_code = code 微信官方提供的临时凭证
         */
        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret, object.get("code"));
        //开始发起网络请求,若依管理系统自带网络请求工具，直接使用即可
        String res = HttpUtils.sendGet(url,params);
        JSONObject jsonObject = JsonUtils.parseObject(res, JSONObject.class);
        String openid = (String) jsonObject.get("openid");
        if (StrUtil.isEmpty(openid)) {
            throw new ServiceException("未获取到openid");
        }
        /**先通过openid来查询是否存在*/
        SysUser jxxcoderWxuser = iJxxcoderWxuserService.selectUserByOpenId(openid);
        if (jxxcoderWxuser == null){
            /**如果不存在就需要授权手机号*/

            /**返回结果集到前段*/
            throw new ServiceException("未找到openid,需手机号校验");
        }else {
            /**返回结果集到前段*/
            String token = iJxxcoderWxuserService.login(jxxcoderWxuser.getUserName(),"admin123");
            return R.ok(token);
        }
    }

    /**
     * openid和手机号
     * @param sysUser
     * @return
     */
    @SaIgnore
    @PostMapping("/wxloginphone")
    public R wxLoginByphone(@RequestBody SysUser sysUser){
        if (null==sysUser|| StringUtils.isBlank(sysUser.getPhonenumber())){
            throw new ServiceException("手机号不能为空");
        }
        SysUser sysUser2 = iJxxcoderWxuserService.selectUserByphonenumber(sysUser.getPhonenumber());
        if(null == sysUser2){
            throw new ServiceException("未找到相关手机号");
        }
        sysUser2.setOpenid(sysUser.getOpenid());
        userService.updateUser(sysUser2);
        String token = iJxxcoderWxuserService.login(sysUser2.getUserName(),"admin123");
        return R.ok(token);
    }



}
